package org.scboy.gateway.decorator;

import cn.hutool.json.JSONObject;
import org.reactivestreams.Publisher;
import org.scboy.gateway.entity.ExportType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.File;
import java.nio.charset.Charset;

/**
 * 
 * 导出数据
 * @author 杨浩
 */
public class ExportDecorator extends ServerHttpResponseDecorator{
	
	private ServerHttpRequest request;
	
	/**
	 * 导出配置
	 */
	private ExportType type;
	/**
	 * 导出模版文件
	 */
	private File exportFile;
	
	public ExportDecorator(File exportFile,ExportType type,ServerHttpRequest request, ServerHttpResponse delegate){
		super(delegate);
		this.request=request;
	}

	@Override
	@SuppressWarnings(value = "unchecked")
	public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
		if(body instanceof Flux) {
			Flux<DataBuffer> fluxBody = (Flux<DataBuffer>) body;

			return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
				DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
				DataBuffer join = dataBufferFactory.join(dataBuffers);

				byte[] content = new byte[join.readableByteCount()];
				join.read(content);
				DataBufferUtils.release(join);//释放掉内存
				
				String bodyStr = new String(content, Charset.forName("UTF-8"));

                //修改响应体
				bodyStr = modifyBody(bodyStr);

				getDelegate().getHeaders().setContentLength(bodyStr.getBytes().length);
				return bufferFactory().wrap(bodyStr.getBytes());
			}));
		}
		return super.writeWith(body);
	}

    //重写这个函数即可
	private String modifyBody(String jsonStr){
		JSONObject json = new JSONObject(jsonStr);
        //TODO...修改响应体
		return json.toString();
	}
}